package cn.icanci.rec.admin.dal.mongodb.mongo;

import cn.icanci.rec.admin.dal.mongodb.common.PageList;
import cn.icanci.rec.admin.dal.mongodb.daointerface.MetadataDAO;
import cn.icanci.rec.admin.dal.mongodb.dateobject.MetadataDO;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

/**
 * @author icanci
 * @since 1.0 Created in 2022/11/11 15:57
 */
@Service("metadataDAO")
public class MongoMetadataDAO extends AbstractBaseDAO<MetadataDO> implements MetadataDAO {
    @Override
    public void insert(MetadataDO metadataDO) {
        super.insert(metadataDO);
        mongoTemplate.insert(metadataDO, COLLECTION_NAME);
    }

    @Override
    public void update(MetadataDO metadataDO) {
        super.update(metadataDO);
        mongoTemplate.save(metadataDO, COLLECTION_NAME);
    }

    @Override
    public List<MetadataDO> queryAll() {
        Criteria criteria = Criteria.where(MetadataColumn.env).is(DEFAULT_ENV);
        Query query = new Query(criteria);
        return mongoTemplate.find(query, COLLECTION_CLASS, COLLECTION_NAME);

    }

    @Override
    public PageList<MetadataDO> pageQuery(MetadataDO metadataDO, int pageNum, int pageSize) {
        Criteria criteria = Criteria.where(MetadataColumn.env).is(DEFAULT_ENV);
        if (StringUtils.isNotBlank(metadataDO.getDomainCode())) {
            criteria.and(MetadataColumn.domainCode).is(metadataDO.getDomainCode());
        }
        if (StringUtils.isNotBlank(metadataDO.getMetadataName())) {
            // 不分区大小写查询，其中操作符"i"：表示不分区大小写
            criteria.and(MetadataColumn.metadataName).regex("^.*" + metadataDO.getMetadataName() + ".*$", "i");
        }

        Query query = new Query(criteria);
        query.with(Sort.by(Sort.Direction.DESC, MetadataColumn.createTime));

        return pageQuery(query, COLLECTION_CLASS, pageSize, pageNum, COLLECTION_NAME);

    }

    @Override
    public MetadataDO queryOneById(String _id) {
        Criteria criteria = Criteria.where(MetadataColumn._id).is(_id);
        criteria.and(MetadataColumn.env).is(DEFAULT_ENV);
        Query query = new Query(criteria);
        return mongoTemplate.findOne(query, COLLECTION_CLASS, COLLECTION_NAME);

    }

    @Override
    public MetadataDO queryByMetadataName(String metadataName, String domainCode) {
        Criteria criteria = Criteria.where(MetadataColumn.metadataName).is(metadataName);
        criteria.and(MetadataColumn.env).is(DEFAULT_ENV);
        criteria.and(MetadataColumn.domainCode).is(domainCode);
        Query query = new Query(criteria);
        return mongoTemplate.findOne(query, COLLECTION_CLASS, COLLECTION_NAME);
    }
}
